//
//  LoginViewController.m
//  iShanggang
//
//  Created by aiShangGang on 2017/3/30.
//  Copyright © 2017年 aishanggang. All rights reserved.
//

#import "LoginViewController.h"
#import "LoginView.h"
#import "PhoneNumberView.h"
#import "MenuView.h"
#import "UIViewExt.h"
#import "UIColor+Hex.h"
#import "NetWorkRequest.h"

#import "RegisterViewController.h"
@interface LoginViewController ()<loginViewDelegate, MenuViewDelegate>

@property (nonatomic, weak) LoginView *loginV;
@property (nonatomic, weak) PhoneNumberView *phoneNumberV;

@end

@implementation LoginViewController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.phoneNumberV.phoneField becomeFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    
//    [BOAssistor setDefaultCountDownValue];
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.view.backgroundColor = cCommonHeaderGrayColor;
    
    [self layoutNavItem];
    [self creatUI];
    // 手机验证码登录通知
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didClickPhoneLoginBtn) name:@"didClickLoginBtn" object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wxAuthAction:) name:WX_AUTH_NOTI object:nil];
}

- (void)layoutNavItem {
    [self ISG_NavigationBarDefaultBackButtonAndNavigationTitle:@"登录"];
    [self ISG_NavigationBarWithBackButtonTitle:nil leftImageNamed:nil andAction:@selector(popToRootViewController)];
    [self ISG_NavigationBarRightBarWithTitle:@"注册" andAction:@selector(registerAction)];
}

- (void)popToRootViewController {
    // 清除用户信息
//    [[ISGUserInfo sharedUserInfo] logout];
    [self dismissViewControllerAnimated:YES completion:nil];
//    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - creat UI
- (void)creatUI {
    MenuView *titleMenuView = [[MenuView alloc] initWithMenuViewWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44) titles:@[@"手机号快捷登录",@"账号密码登录"] index:1];
    [self menuView:titleMenuView didSelectedIndex:1];
    titleMenuView.delegate = self;
    titleMenuView.selectedColor = [UIColor colorWithHex:0xd23023];
    titleMenuView.unselectedColor = [UIColor colorWithHex:0x333333];
    [self.view addSubview:titleMenuView];
    
    LoginView *loginV = [[LoginView alloc] initWithFrame:CGRectMake(0, titleMenuView.bottom, self.view.width, 180)];
    loginV.delegate = self;
    [self.view addSubview:loginV];
    self.loginV = loginV;
    
    PhoneNumberView *phoneNumberV = [[PhoneNumberView alloc] initWithFrame:CGRectMake(0, titleMenuView.bottom, self.view.width, 180)];
    [self.view addSubview:phoneNumberV];
    self.phoneNumberV = phoneNumberV;
    
}

#pragma mark - MenuViewDelegate
- (void)menuView:(MenuView *)menuView didSelectedIndex:(NSInteger)index {
    if (index == 1) {
        [self.view insertSubview:self.phoneNumberV belowSubview:self.loginV];
        [self.loginV.accountField becomeFirstResponder];
    } else if (index == 0) {
        [self.view insertSubview:self.loginV belowSubview:self.phoneNumberV];
        [self.phoneNumberV.phoneField becomeFirstResponder];
    }
}

#pragma mark - 注册
- (void)registerAction {
    [self.view endEditing:YES];
    RegisterViewController *vc = [RegisterViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 密码登录代理事件
- (void)didClickLoginBtn {
    [self.view endEditing:YES];
    [self accountAndEmployLogin];
}

- (void)accountAndEmployLogin {
    NSString *account = self.loginV.accountField.text;
    NSString *psw = self.loginV.passwordField.text;
    //输入只能是字母和数字-------------
    NSCharacterSet *s = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"];
    s = [s invertedSet];
    NSRange r = [account rangeOfCharacterFromSet:s];
    if (r.location != NSNotFound) {
        self.noticeText = @"不能输入字母数字以外的字符";
        return;
    } else if (account.length == 0) {
        self.noticeText = @"账号不能为空";
        return;
    } else if (psw.length == 0) {
        self.noticeText = @"密码不能为空";
        return;
    } else if (psw.length < 4) {
        self.noticeText = @"密码不能小于4位";
        return;
    } else if (psw.length > 20) {
        self.noticeText = @"密码不能大于20位";
        return;
    } else {
        __weak typeof(self) weakSelf = self;
//        ISGUserInfo *userInfo = [ISGUserInfo sharedUserInfo];
        [NetWorkRequest postNetRequestData:@"" parmeters:@{@"username":account,@"password":psw} response:^(NSDictionary *response) {
            if (response) {
                [weakSelf progressHUDShowWithCompleteText:@"登录成功" isSucceed:YES];
                //保存数据---进行一系列的操作----------
                [self dismissViewControllerAnimated:YES completion:nil];
            }else {
                [weakSelf progressHUDHideImmediately];
            }
        } netError:^(NSError *error) {
            [weakSelf progressHUDShowWithCompleteText:@"登录失败，请重新登录" isSucceed:NO];
        }];
    }
}

#pragma mark - 验证码登录通知事件
- (void)didClickPhoneLoginBtn {
    [self.view endEditing:YES];
    NSString *account = self.phoneNumberV.phoneField.text;
    NSString *code = self.phoneNumberV.codeField.text;
    
    __weak typeof(self) weakSelf = self;
    NSDictionary *reqDic = @{@"code":code,@"mobile":account};
    //加密后的数据-----
//    NSDictionary *pramas = [ASGNetWorkEngine paraWithSid:@"fastLoginRegist" requestData:reqDic];
    
    [NetWorkRequest postNetRequestData:@"" parmeters:reqDic response:^(NSDictionary *response) {
        if (response) {
            [weakSelf progressHUDShowWithCompleteText:@"登录成功" isSucceed:YES];
            //保存数据---进行一系列的操作----------
            [self dismissViewControllerAnimated:YES completion:nil];
        }else {
//            NSDictionary *retDic = [ASGNetWorkEngine dictionaryWithDESString:[result objectForKey:@"retData"]];
            [self progressHUDShowWithCompleteText:[response objectForKey:@"message"] isSucceed:NO];
        }
    } netError:^(NSError *error) {
        [weakSelf progressHUDShowWithCompleteText:@"登录失败，请重新登录" isSucceed:NO];
    }];
    
}

#pragma mark - 微信认证通知----在delegata里面发送通知---------------
/*if ([resp isKindOfClass:[SendAuthResp class]]) {
     1.授权登录(ERR_OK = 0(用户同意) ERR_AUTH_DENIED = -4（用户拒绝授权）ERR_USER_CANCEL = -2（用户取消）)
     2.获取access_token
    if (resp.errCode == 0) {
        SendAuthResp *resp2 = (SendAuthResp *)resp;
        NSString *code = resp2.code;
        NSDictionary *dic = @{@"code":code};
        [[NSNotificationCenter defaultCenter] postNotificationName:WX_AUTH_NOTI object:self userInfo:dic];
    }
}*/
- (void)wxAuthAction:(NSNotification *)noti {
    NSDictionary *userInfo = noti.userInfo;
    __weak typeof(self) weakSelf = self;
    [NetWorkRequest postNetRequestData:@"" parmeters:userInfo response:^(NSDictionary *response) {
        if (response) {
            [weakSelf progressHUDShowWithCompleteText:@"登录成功" isSucceed:YES];
            //保存数据---进行一系列的操作----------
            [self dismissViewControllerAnimated:YES completion:nil];
        }else {
            //            NSDictionary *retDic = [ASGNetWorkEngine dictionaryWithDESString:[result objectForKey:@"retData"]];
            [self progressHUDShowWithCompleteText:[response objectForKey:@"message"] isSucceed:NO];
        }
    } netError:^(NSError *error) {
        [weakSelf progressHUDShowWithCompleteText:@"登录失败，请重新登录" isSucceed:NO];
    }];
    
//    [self postURLRequestWithURL:@"" sessionID:NO HUDLabelText:@"正在加载..." params:userInfo completeBlock:^(NSDictionary *result) {
//        @strongify(self)
//        [self progressHUDHideImmediately];
//        if ([result[@"status"] integerValue] == 0) {
//            NSDictionary *contents = result[@"contents"];
//            BOOL bindFlag = [contents[@"bindUserPhoneFlag"] boolValue];
//            if (bindFlag == NO) {
//                NSString *openId = contents[@"openId"];
//
//                WXBindPhoneVC *vc = [[WXBindPhoneVC alloc] init];
//                vc.openId = openId;
//                [self.navigationController pushViewController:vc animated:YES];
//            } else {
//                NSString *sessionId = contents[@"sessionId"];
//
////                [ISGUserInfo sharedUserInfo].sessionID = sessionId;
////                [ISGUserInfo sharedUserInfo].bindPhoneFlag = YES;
////                [[ISGUserInfo sharedUserInfo] saveUserInfo];
////
////                [[UserService sharedInstance] requestPersonInfo];
//                [self progressHUDShowWithCompleteText:@"登录成功" isSucceed:YES];
//
//                [self.navigationController popViewControllerAnimated:YES];
//            }
//        } else {
//            self.noticeText = result[@"msg"];
//        }
//    } failedBlock:^(NSError *error) {
//        @strongify(self)
//        [self progressHUDHideImmediately];
//    }];
}

@end
